from django.conf import settings
import os


class ModelsSave:
    def __init__(self, old_obj, new_obj, fields):
        self.old_obj = old_obj
        self.new_obj = new_obj
        self.fields = fields

    def run(self):
        if self.old_obj:
            for field in self.fields:
                if getattr(self.old_obj, field) != getattr(self.new_obj, field):
                    obj_paths = getattr(self.old_obj, field).name
                    if obj_paths:
                        try:
                            obj_paths = obj_paths.split('/')
                        except Exception as e:
                            pass
                        path_name = os.path.join(settings.MEDIA_ROOT, *obj_paths)
                        if os.path.isfile(path_name):
                            os.remove(path_name)
